package org.xdq.demo.service.impl;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xdq.demo.dao.EmpDao;
import org.xdq.demo.dto.EmpDto;
import org.xdq.demo.dto.EmpQueryDto;
import org.xdq.demo.util.MyUtils;

import javax.annotation.PostConstruct;
import java.util.Map;

@Service
@Transactional
public class EmpServiceImpl implements org.xdq.demo.service.EmpService {

    private static final Object LOCK = new Object();
    private int maxId;

    @PostConstruct
    public void getMaxId() {

       maxId = empDao.findMaxIntegerId();

    }

    private String getNewId(){
        int newIntId;
        synchronized (LOCK) {
            newIntId = ++maxId;
        }
        return String.format("%05d",newIntId);
    }


    @Autowired
    private EmpDao empDao;

    @Override
    public Map<String,Object> getEmpPage(EmpQueryDto dto) {
        try {
            return MyUtils.getPage(dto, () -> empDao.findEmpList(dto));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void addNewEmp(EmpDto empDto){
        empDto.setE_id(getNewId());
        empDto.setE_status(0);
        empDao.insertNewEmp(empDto);

    }

    @Override
    public void removeEmp(String[] ids){
       empDao.deleteEmpByIds(ids);

    }

    @Override
    public void changeEmpStatus(String eId, int newStatus) {
        EmpDto dto = new EmpDto();
        dto.setE_id(eId);
        dto.setE_status(newStatus);
        empDao.updateEmp(dto);

    }
}
